package com.xky.ui.module.supplierManagement;

import com.xky.pojo.Supplier;
import com.xky.ui.module.supplierManagement.select.SelectSupplier;
import com.xky.ui.module.supplierManagement.add.AddSuppliers;
import com.xky.ui.module.supplierManagement.delete.DeleteSupplier;
import com.xky.ui.module.supplierManagement.update.UpdateSupplier;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;

/**
 * 供应商信息管理界面类
 */
public class SupplierMassage {

    // 表格组件
    private static JTable table;
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
    private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
    
    // 日期时间格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 创建供应商信息面板
     * @param refreshAction 刷新操作
     * @return 供应商信息面板
     */
    public static JPanel createWarehouseInfoPanel(Runnable refreshAction) {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建顶部面板（标题和按钮）
        JPanel topPanel = new JPanel(new BorderLayout());
        
        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JLabel titleLabel = new JLabel("供应商基本信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        // 分割线
        JSeparator separator = new JSeparator();
        separator.setPreferredSize(new Dimension(1200, 2));
        separator.setBackground(SEPARATOR_COLOR);
        
        // 操作按钮面板
        JPanel buttonPanel = createButtonPanel(refreshAction);
        
        // 添加到顶部面板
        topPanel.add(titlePanel, BorderLayout.NORTH);
        topPanel.add(separator, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 表格
        JScrollPane scrollPane = createSupplierTable();
        
        // 添加到主面板
        panel.add(topPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    /**
     * 创建按钮面板
     * @param refreshAction 刷新操作
     * @return 按钮面板
     */
    private static JPanel createButtonPanel(Runnable refreshAction) {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        buttonPanel.setBackground(SECONDARY_COLOR);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

        // 创建按钮
        JButton addButton = createStyledButton("添加", BUTTON_COLOR);
        JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
        JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
        JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
        JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);

        // 添加事件监听器
        addButton.addActionListener(e -> {
            new AddSuppliers();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        deleteButton.addActionListener(e -> {
            new DeleteSupplier();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        updateButton.addActionListener(e -> {
            new UpdateSupplier();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        queryButton.addActionListener(e -> showSearchDialog());

        refreshButton.addActionListener(e -> {
            SelectSupplier.resetSearchStatus();
            if (refreshAction != null) {
                refreshAction.run();
                updateStatusMessage("供应商数据已刷新");
                
                // 启动自动刷新
                if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
                    autoRefreshTimer.start();
                }
            }
        });

        // 添加按钮到面板
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(queryButton);
        buttonPanel.add(refreshButton);

        return buttonPanel;
    }
    
    /**
     * 创建统一风格的按钮
     * @param text 按钮文本
     * @param bgColor 背景颜色
     * @return 按钮对象
     */
    private static JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(100, 35));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        return button;
    }

    /**
     * 创建供应商表格
     * @return 包含表格的滚动面板
     */
    public static JScrollPane createSupplierTable() {
        // 表格列名
        String[] columnNames = {"供应商ID", "供应商编码", "供应商名称", "联系人姓名", "联系人电话", "联系人邮箱", "地址", "是否合作", "创建时间", "更新时间"};

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 设置表格不可编辑
            }
        };

        // 创建表格
        table = new JTable(model);
        table.setRowHeight(30);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
        table.getTableHeader().setBackground(PRIMARY_COLOR);
        table.getTableHeader().setForeground(Color.BLACK);
        // 确保表头文本可见
        table.getTableHeader().setOpaque(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setAutoCreateRowSorter(true);
        table.setShowGrid(true);
        table.setGridColor(new Color(230, 230, 230));

        // 设置表格列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(80);
        table.getColumnModel().getColumn(1).setPreferredWidth(100);
        table.getColumnModel().getColumn(2).setPreferredWidth(120);
        table.getColumnModel().getColumn(3).setPreferredWidth(100);
        table.getColumnModel().getColumn(4).setPreferredWidth(120);
        table.getColumnModel().getColumn(5).setPreferredWidth(150);
        table.getColumnModel().getColumn(6).setPreferredWidth(150);
        table.getColumnModel().getColumn(7).setPreferredWidth(80);
        table.getColumnModel().getColumn(8).setPreferredWidth(150);
        table.getColumnModel().getColumn(9).setPreferredWidth(150);

        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        scrollPane.getViewport().setBackground(Color.WHITE);

        return scrollPane;
    }

    /**
     * 更新表格数据
     * @param table 表格
     * @param supplierList 供应商列表
     */
    public static void updateTableData(JTable table, List<Supplier> supplierList) {
        if (table == null || supplierList == null) {
            return;
        }
        
        DefaultTableModel model = (DefaultTableModel) table.getModel();

        // 清空表格中现有的数据
        model.setRowCount(0);

        for (Supplier supplier : supplierList) {
            String createdTimeStr = supplier.getCreatedTime() != null ? 
                supplier.getCreatedTime().format(DATE_FORMATTER) : "";
            String updatedTimeStr = supplier.getUpdatedTime() != null ? 
                supplier.getUpdatedTime().format(DATE_FORMATTER) : "";
                
            model.addRow(new Object[]{
                    supplier.getSupplierId(),
                    supplier.getSupplierCode(),
                    supplier.getSupplierName(),
                    supplier.getContactName(),
                    supplier.getContactPhone(),
                    supplier.getContactEmail(),
                    supplier.getAddress(),
                    supplier.getIsActive() ? "是" : "否",
                    createdTimeStr,
                    updatedTimeStr
            });
        }

        // 触发表格数据刷新
        model.fireTableDataChanged();
    }

    /**
     * 显示查询对话框
     */
    private static void showSearchDialog() {
        // 创建对话框
        JDialog searchDialog = new JDialog((Frame)null, "查询供应商", true);
        searchDialog.setSize(900, 550);
        searchDialog.setLocationRelativeTo(null);
        searchDialog.setLayout(new BorderLayout());

        // 创建顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 10, 15));
        topPanel.setBackground(SECONDARY_COLOR);

        // 创建单选按钮组
        JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        radioPanel.setOpaque(false);
        
        ButtonGroup buttonGroup = new ButtonGroup();
        JRadioButton idRadio = new JRadioButton("按供应商ID查询", true);
        JRadioButton keywordRadio = new JRadioButton("关键字查询");
        
        idRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        keywordRadio.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        idRadio.setOpaque(false);
        keywordRadio.setOpaque(false);

        buttonGroup.add(idRadio);
        buttonGroup.add(keywordRadio);

        radioPanel.add(idRadio);
        radioPanel.add(keywordRadio);

        topPanel.add(radioPanel, BorderLayout.NORTH);

        // 创建搜索条件面板
        JPanel searchPanel = new JPanel(new BorderLayout(10, 5));
        searchPanel.setOpaque(false);
        
        JLabel searchLabel = new JLabel("查询条件: ");
        searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        
        JTextField searchField = new JTextField(20);
        searchField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        searchField.setPreferredSize(new Dimension(200, 30));
        
        JButton searchButton = createStyledButton("搜索", SEARCH_BUTTON_COLOR);

        JPanel searchFieldPanel = new JPanel(new BorderLayout(10, 0));
        searchFieldPanel.setOpaque(false);
        searchFieldPanel.add(searchLabel, BorderLayout.WEST);
        searchFieldPanel.add(searchField, BorderLayout.CENTER);
        searchFieldPanel.add(searchButton, BorderLayout.EAST);
        searchPanel.add(searchFieldPanel, BorderLayout.NORTH);

        // 添加提示信息
        JLabel tipLabel = new JLabel("提示: 关键字查询将搜索 供应商编码/ 供应商名称/ 联系人姓名/ 联系人电话/ 联系人邮箱/ 地址/ 是否合作");
        tipLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
        tipLabel.setForeground(Color.GRAY);
        tipLabel.setBorder(BorderFactory.createEmptyBorder(8, 0, 0, 0));
        searchPanel.add(tipLabel, BorderLayout.CENTER);

        topPanel.add(searchPanel, BorderLayout.CENTER);
        searchDialog.add(topPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"供应商ID", "供应商编码", "供应商名称", "联系人姓名", "联系人电话", "联系人邮箱", "地址", "是否合作", "创建时间", "更新时间"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        JTable resultTable = new JTable(tableModel);
        resultTable.setRowHeight(30);
        resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
        resultTable.getTableHeader().setBackground(Color.lightGray);
        resultTable.getTableHeader().setForeground(Color.BLACK);
        // 确保表头文本可见
        resultTable.getTableHeader().setOpaque(true);
        resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultTable.setShowGrid(true);
        resultTable.setGridColor(new Color(230, 230, 230));

        JScrollPane scrollPane = new JScrollPane(resultTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
        scrollPane.getViewport().setBackground(Color.WHITE);
        searchDialog.add(scrollPane, BorderLayout.CENTER);

        // 创建底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        buttonPanel.setBackground(SECONDARY_COLOR);
        
        JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
        JButton cancelButton = createStyledButton("取消", new Color(231, 76, 60));

        buttonPanel.add(selectButton);
        buttonPanel.add(cancelButton);
        searchDialog.add(buttonPanel, BorderLayout.SOUTH);

        // 设置按钮动作
        searchButton.addActionListener(_ -> {
            String searchText = searchField.getText().trim();
            if (searchText.isEmpty()) {
                JOptionPane.showMessageDialog(searchDialog, "请输入查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            List<Supplier> resultList = new ArrayList<>();

            try {
                if (idRadio.isSelected()) {
                    try {
                        int id = Integer.parseInt(searchText);
                        Supplier result = SelectSupplier.selectWarehousesById(id);
                        if (result != null) {
                            resultList.add(result);
                        }
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(searchDialog, "ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                } else if (keywordRadio.isSelected()) {
                    // 获取关键字搜索结果
                    List<Supplier> suppliers = SelectSupplier.searchSupplierByKeyword(searchText);
                    if (suppliers != null && !suppliers.isEmpty()) {
                        resultList.addAll(suppliers);
                    }
                }

                // 更新表格数据
                tableModel.setRowCount(0);

                if (!resultList.isEmpty()) {
                    for (Supplier supplier : resultList) {
                        String createdTimeStr = supplier.getCreatedTime() != null ? 
                            supplier.getCreatedTime().format(DATE_FORMATTER) : "";
                        String updatedTimeStr = supplier.getUpdatedTime() != null ? 
                            supplier.getUpdatedTime().format(DATE_FORMATTER) : "";
                            
                        tableModel.addRow(new Object[]{
                                supplier.getSupplierId(),
                                supplier.getSupplierCode(),
                                supplier.getSupplierName(),
                                supplier.getContactName(),
                                supplier.getContactPhone(),
                                supplier.getContactEmail(),
                                supplier.getAddress(),
                                supplier.getIsActive() ? "是" : "否",
                                createdTimeStr,
                                updatedTimeStr
                        });
                    }
                } else {
                    JOptionPane.showMessageDialog(searchDialog, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(searchDialog, "查询发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        });

        cancelButton.addActionListener(e -> searchDialog.dispose());

        selectButton.addActionListener(e -> {
            int selectedRow = resultTable.getSelectedRow();
            if (selectedRow >= 0) {
                // 获取选中的行数据
                int supplierId = (int) tableModel.getValueAt(selectedRow, 0);

                // 获取选中的供应商数据
                Supplier supplier = SelectSupplier.selectWarehousesById(supplierId);
                List<Supplier> supplierList = new ArrayList<>();
                if (supplier != null) {
                    supplierList.add(supplier);
                }

                if (!supplierList.isEmpty()) {
                    // 清空主表格并只显示选中的供应商
                    updateTableData(table, supplierList);

                    // 停止自动刷新
                    if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
                        autoRefreshTimer.stop();
                    }

                    // 更新状态消息
                    updateStatusMessage("已选择供应商: " + supplierList.get(0).getSupplierName());
                }

                searchDialog.dispose();
            } else {
                JOptionPane.showMessageDialog(searchDialog, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        // 设置回车键触发搜索按钮
        searchDialog.getRootPane().setDefaultButton(searchButton);

        // 显示对话框
        searchDialog.setVisible(true);
    }
}
